﻿using System.Collections;
using com.guojin.mj.net;
using com.guojin.mj.net.message.login;
using UnityEngine;
using UnityEngine.UI;

public class LoginPage : EventManager
{
    public Button wxLoginBtn;
    public Button visitorLoginBtn;
    public Toggle agreeTog;
    public Button agreeBtn;
   
    public override void InformationSetting()
    {
        //PlayerPrefs.DeleteAll();
#if UNITY_ANDROID && !UNITY_EDITOR
        LoginAndShare.Controller.GetRoomNoFromAD();
#elif UNITY_IPHONE
#endif
        TestNetworkConnected();
    }

    void Start()
    {
        AddListenerToButton(wxLoginBtn, wxLoginBtnClick);
        AddListenerToButton(visitorLoginBtn, VisitorLoginBtnClick);
        AddListenerToButton(agreeBtn, agreeBtnClick);
    }

    void TestNetworkConnected()
    {
        //判断网络的连通性
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            TooL.ShowTipsPage("无法连接网络！请打开wifi或4G网络后重试。", TooL.TipsPageType.noCancelPage, () =>
            {
                TestNetworkConnected();
            });
        }
        else
        {
            StartConnectSever();
        }
    }

    private void StartConnectSever()
    {
        StartCoroutine(ConnectSever());
        StartCoroutine(StartCheckToken());
    }

    IEnumerator ConnectSever()
    {
        if (!SocketMgr.GetInstance().isNetOpen)
        {
            SocketMgr.GetInstance().InitNet();
            yield return new WaitForSeconds(3f);
            StartCoroutine(ConnectSever());
        }
    }

    IEnumerator StartCheckToken()
    {
        yield return new WaitUntil(() => SocketMgr.GetInstance().isNetOpen);
        StopAllCoroutines();
        CheckToken();
    }

    /// <summary>
    /// 开始自动登录，判断使用token登录还是wx登录
    /// </summary>
    void CheckToken()
    {
        //PlayerPrefs.DeleteAll();                  //匿名登录删除token
        if (SocketMgr.GetInstance().isNetOpen)
        {
            string token = PlayerPrefs.GetString(DefaultKeyConst.VisitorTokenKey);
            if (!token.Equals(""))
            {
                string longitude = GameData.GetInstance().longitude;        //启动游戏时由jar包中调用获取方法
                string latitude = GameData.GetInstance().latitude;
                Debug.Log("longitude>>" + longitude + "  latitude>>" + latitude);

                MessageManager.GetInstance().SendMsg78("TOKEN", token, null, longitude, latitude);

                StartCoroutine(TokenUselessCallWx());                               //1.5s内没反应说明token失效再次吊起微信登录
            }
            else
            {
                wxLoginBtn.gameObject.SetActive(true); 
            }
        }
        else
        {
            StartConnectSever();
        }
    }

    //token无效时是否允许吊起微信（token登录后，1.5秒无反应如果允许就吊起微信登录）
    public bool IsNeedWxPutOn = true;
    public IEnumerator TokenUselessCallWx()
    {
        yield return new WaitForSeconds(1.5f);
#if UNITY_EDITOR
        MessageManager.GetInstance().SendMsg78("ANONYMOUS", null, null, "34.7545", null);
#else
        if (IsNeedWxPutOn)
        {
            LoginAndShare.Controller.OnClickWXLogin();
        }
#endif
    }

    void wxLoginBtnClick()
    {
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            TooL.ShowTipsPage("无法连接网络！请打开wifi或4G网络后重试。", TooL.TipsPageType.noCancelPage, () =>
            {
                TestNetworkConnected();
            });
        }
        else
        {
            Debug.Log("wxLoginBtnClick");

            if (agreeTog.GetComponent<Toggle>().isOn)
            {
                if (isWXLoginBtnClick == true)
                {
                    isWXLoginBtnClick = false;

#if UNITY_EDITOR || ANONYMOUS    //这里注意是匿名登录/* || UNITY_ANDROID  
                    MessageManager.GetInstance().SendMsg78("ANONYMOUS", null, null, "34.7545", null);
#elif WX_SDK
               LoginAndShare.Controller.OnClickWXLogin();
#endif

                }
            }
            else
            {
                TooL.ShowTipsPage("请勾选同意用户协议，感谢您的配合，祝您游戏愉快!",TooL.TipsPageType.noCancelPage, () => { agreeTog.GetComponent<Toggle>().isOn = true; });
            }
        }
    }

    void VisitorLoginBtnClick()
    {
        PlayerPrefs.DeleteAll();
        string token = PlayerPrefs.GetString(DefaultKeyConst.VisitorTokenKey);                //这里写token可以用提供的token登录
        string longitude = GameData.GetInstance().longitude;
        string latitude = GameData.GetInstance().latitude;
        if (!token.Equals(""))
        {
            MessageManager.GetInstance().SendMsg78("TOKEN", token, null, longitude, latitude);
        }
        else
        {
            MessageManager.GetInstance().SendMsg78("ANONYMOUS", null, null, longitude, latitude);
        }
    }

    void agreeBtnClick()
    {
        UIManager.ChangeUI(UIManager.PageState.UserAgreeMentPage, (GameObject obj) =>
        {
            obj.GetComponent<UserAgreeMentPage>().InformationSetting();
        });
    }

    bool isWXLoginBtnClick = true;
    float timer = 0;
    void Update()
    {
        if (!isWXLoginBtnClick)
        {
            timer += Time.deltaTime;
            if (timer > 3)
            {
                timer = 0;
                isWXLoginBtnClick = true;
            }
        }
    }
}